<template>
  <view class="container">
    <ve-form ref="veFormRef" :model="form" :rules="rules">
      <!-- 情况1：未带入车辆，需要手动选择 -->
      <ve-card title="车辆基本信息" type="none" v-if="pageFrom == 'indexTool'">
        <ve-form-item label="车牌号" :borderBottom="false" prop="licenseNo" required>
          <remote-select type="licenseNo" :label="form.licenseNo" @change="changeLicenseNo" v-model="form.carId" allowClear />
        </ve-form-item>
        <car-info-shadow v-if="carInfo.licenseNo" :info="carInfo" />
        <view :style="carInfo.licenseNo ? 'height: 24rpx;' : ''"></view>
      </ve-card>
      <!-- 情况2：带入保养id|车辆id|订单id，无需手动选择 -->
      <CarInfo :info="carInfo" v-else>
        <ve-cell-val v-if="form.id" label="保险状态" :value="carInfo.insureStatusStr" />
      </CarInfo>
      <ve-card title="保险信息" type="none" :customStyle="{ marginBottom: 0 }">
        <InsureItem :info="form" />
      </ve-card>
    </ve-form>
    <ve-bottom-box>
      <ve-button type="primary" :loading="okLoading" @click="formSubmit">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import { ref } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import CarInfo from '@/pages/common/components/car-info.vue'
  import CarInfoShadow from '@/pages/common/components/car-info-shadow.vue'
  import InsureItem from './components/insure-item.vue'
  import { getCarDetail } from '@/api/asset/car-manager'
  import { addApi, editApi, getDetailApi } from '@/api/asset/car-insure'
  import { isMobile } from '@/utils/validate'
  import dayjs from 'dayjs'

  const form = ref({})
  const carInfo = ref({})

  const rules = ref({
    licenseNo: {
      required: true,
      message: '请选择车牌号',
    },
    siteId: {
      required: true,
      message: '请选择保险单关联门店',
    },
    insureCompany: {
      required: true,
      message: '请选择保险公司',
    },
    experiencedPhone: {
      required: false,
      validator: (_, value, callback) => {
        if (value) {
          if (isMobile(value)) {
            callback()
          } else {
            callback(new Error('支持输入11位数字'))
          }
        } else {
          callback()
        }
      },
    },
    lifeSpan: {
      required: true,
      message: '请选择有效期',
      validator: (_, value, callback) => {
        if (form.value.beginDate && form.value.endDate) {
          callback()
        } else {
          callback(new Error('请选择有效期'))
        }
      },
    },
  })

  // 选择车牌号
  const changeLicenseNo = (carId, option = {}) => {
    form.value.carId = carId
    form.value.licenseNo = option.licenseNo
    form.value.siteId = option.siteId
    form.value.siteName = option.siteName
    carInfo.value = option
  }

  /**
   * options: { id: 保险id, carId: 车辆id, insureKind: 险种 0交强 1商业 }
   */
  const pageFrom = ref('')
  onLoad((options) => {
    const { id, carId, insureKind, from } = options
    form.value.insureKind = insureKind
    pageFrom.value = from
    // 设置 title
    uni.setNavigationBarTitle({
      title: id ? (insureKind == 0 ? '编辑交强险' : '编辑商业险') : insureKind == 0 ? '新增交强险' : '新增商业险',
    })
    // 编辑保险
    if (id) {
      getDetailApi({ id }).then((res) => {
        const result = res.result
        // 保险信息中包含展示用的车辆信息
        carInfo.value = result
        // 商业险需要处理 carInsureDetail 默认有一条
        let insureKind = result.insureKind
        if (insureKind == 1) {
          let carInsureDetail = result.carInsureDetail
          if (!carInsureDetail || carInsureDetail.length == 0) {
            result.carInsureDetail = [{}]
          }
        }
        // 赋值给表单
        form.value = result
      })
      return
    }
    // 从车辆新增
    if (carId) {
      // 商业险
      if (insureKind == 1) {
        form.value.carInsureDetail = [{}]
      }

      // 获取车辆详情
      getCarDetail({ id: carId }).then((res) => {
        const result = res.result || {}
        carInfo.value = result
        // 设置默认的保险单关联门店
        form.value.siteId = result.siteId
        form.value.siteName = result.siteName
      })
      return
    }
  })
  const veFormRef = ref(null)
  const okLoading = ref(false)

  // 判断是否录入: 0 被认为是有效输入 '' 被认为是无效输入
  const isValid = (val) => {
    return !!val || (typeof val == 'number' && val === 0)
  }
  // 构建请求参数
  const buildParams = () => {
    let param = { ...form.value }
    // 处理 carInsureDetail 投保信息
    if (param.carInsureDetail?.length > 0) {
      let carInsureDetail = JSON.parse(JSON.stringify(param.carInsureDetail))
      for (var i = 0; i < carInsureDetail.length; i++) {
        let item = carInsureDetail[i]
        let { insureKindType, insuredSum, insureAmt } = item
        if (!isValid(insureKindType) && !isValid(insuredSum) && !isValid(insureAmt)) {
          carInsureDetail.splice(i, 1)
          i--
        }
      }
      param.carInsureDetail = carInsureDetail
    }

    return param
  }
  // 校验保险结束日期是否大于开始日期
  const checkEndDate = (param) => {
    return new Promise((resolve) => {
      // 如果是编辑，则不校验
      if (param.id) {
        resolve()
      } else {
        // 保单信息
        const insureInfo = param.insureAddList[0]
        const { endDate, insureKind } = insureInfo
        // 车辆的保单到期日
        const { compulsoryEndDate, businessEndDate } = carInfo.value
        // 交强险
        if (insureKind == 0) {
          if (compulsoryEndDate && dayjs(endDate).isBefore(compulsoryEndDate)) {
            uni.showModal({
              title: '提示',
              content: '当前交强险保单的到期日早于车辆上的交强险到期日，请确认是否新增？',
              confirmText: '确认',
              success: function (res) {
                if (res.confirm) {
                  resolve()
                }
              },
            })
          } else {
            resolve()
          }
        }
        // 商业险
        if (insureKind == 1) {
          if (businessEndDate && dayjs(endDate).isBefore(businessEndDate)) {
            uni.showModal({
              title: '提示',
              content: '当前商业险保单的到期日早于车辆上的商业险到期日，请确认是否新增？',
              confirmText: '确认',
              success: function (res) {
                if (res.confirm) {
                  resolve()
                }
              },
            })
          } else {
            resolve()
          }
        }
      }
    })
  }
  const formSubmit = () => {
    veFormRef.value.validate((valid) => {
      if (valid) {
        let api = addApi
        let param = {}
        // 编辑
        if (form.value.id) {
          api = editApi
          param = buildParams()
        } else {
          // 新增
          param = {
            carId: carInfo.value.id,
            insureAddList: [buildParams()],
          }
        }
        checkEndDate(param).then(() => {
          okLoading.value = true
          api(param)
            .then((res) => {
              uni.showToast({
                icon: 'none',
                title: res.message,
              })
              if (pageFrom.value == 'carManagerList') {
                // 1 商业险 0 交强险
                uni.redirectTo({
                  url: `/pages/asset/car-manager/detail/${form.value.insureKind == 1 ? 'business-insure-info' : 'jq-insure-info'}?id=${
                    carInfo.value.id
                  }`,
                })
              }
              // 常用工具增加保险成功后，跳转至保险列表
              else if (pageFrom.value == 'indexTool') {
                // 先跳转到车辆详情页
                uni.redirectTo({
                  url: `/pages/asset/car-manager/detail/index?id=${carInfo.value.id}`,
                  success() {
                    // 再跳转到车辆详情>保险列表页
                    uni.navigateTo({
                      url: `/pages/asset/car-manager/detail/${form.value.insureKind == 1 ? 'business-insure-info' : 'jq-insure-info'}?id=${
                        carInfo.value.id
                      }`,
                    })
                  },
                })
              } else {
                uni.navigateBack()
              }
              uni.$emit('carInsure_getList')
              uni.$emit('carEdit_insureAddOk', param)
            })
            .finally(() => {
              okLoading.value = false
            })
        })
      }
    })
  }
</script>

<style lang="scss" scoped>
  .container {
    background: #f7f8fa;
    padding: 24rpx;
  }
  .insure-detail-item {
    background: #f7f8fa;
    .insure-detail-item-title {
      height: 88rpx;
      padding: 0 24rpx;
      background: #f0f1f3;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .insure-detail-item-title-text {
        font-size: 30rpx;
        font-weight: 600;
        color: #191c27;
      }
    }
    .insure-detail-item-content {
      padding: 0 24rpx;
    }
  }
  .insure-detail-item + .insure-detail-item {
    margin-top: 32rpx;
  }
  .add-insure-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 88rpx;
    background: #f3f7ff;
    border-radius: 4rpx 4rpx 4rpx 4rpx;
    border: 2rpx solid #3072f6;
    margin-top: 32rpx;
    margin-bottom: 32rpx;
    .add-insure-btn-text {
      font-size: 30rpx;
      color: #3072f6;
      line-height: 1;
      margin-left: 18rpx;
    }
  }
</style>
